using Assets.Scripts.Entities;
using Assets.Scripts.SO;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Assets.Scripts.Controllers
{
    internal class VisitorsController : MonoBehaviour
    {
        [SerializeField] private ScriptableUpgrade _limitUpgrade;
        [SerializeField] private Transform _jumpingPoint;
        [SerializeField] private Child _childPrefab;
        [SerializeField] private List<ScriptableChild> _allChilds;

        private List<ScriptableChild> _unlockedChilds = new List<ScriptableChild>();
        private Child _nextChild;

        public void Stop()
        {
            CancelInvoke(nameof(SpawnChild));
        }

        private void Start ()
        {
            _unlockedChilds = _allChilds.Where(x => x.UnlockDay <= DayController.Day).ToList();
            InvokeRepeating(nameof(SpawnChild), 0f, 1.5f);
        }

        private void SpawnChild()
        {
            if (_nextChild == null)
            {
                var scriptableChild = _unlockedChilds[Random.Range(0, _unlockedChilds.Count)];
                _nextChild = Instantiate(_childPrefab, _jumpingPoint.transform.position, Quaternion.identity, null);
                _nextChild.GetComponent<Rigidbody2D>().isKinematic = true;
                _nextChild.ScriptableChild = scriptableChild;

                return;
            }

            var childs = FindObjectsOfType<Child>().Where(x => x.CurrentState == Child.State.Jumping).ToList();
            if (childs.Count < _limitUpgrade.Value)
            {
                ThrowChild();
                _nextChild = null;
            }
        }

        private void ThrowChild()
        {
            _nextChild.StartJumping();
            _nextChild.GetComponent<Rigidbody2D>().AddForce(new Vector2(1, 1) * Random.Range(1, 3f), ForceMode2D.Impulse);
        }
    }
}
